package com.fxtcn.core;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import com.fxtcn.utils.FileUtil;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

/**
 * @author： 张勇军
 * @E-Mail: zhangyongjun@roadrover.cn
 * @Date ： 2011-5-19 下午07:28:35
 * @Description 图片的延迟加载 以及本地缓存
 */
public class LazyImageLoader {
	private static final String TAG = "LazyImageLoader";
	private static boolean isLocalSave = false; // 是否本地保存
	private static String filePath = "";// 文件路径 eg:Constants.ICON_PATH
	private HashMap<String, SoftReference<Drawable>> imageCache;

	public LazyImageLoader(boolean isSave, String fPath) {
		isLocalSave = isSave;
		filePath = fPath;
		imageCache = new HashMap<String, SoftReference<Drawable>>();
	}

	public Drawable loadDrawable(final String imageUrl,
			final LazyImageCallback imageCallback) {

		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
			}
		};

		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			Drawable drawable = softReference.get();
			if (drawable != null) {
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
				return drawable;
			}
		}

		new Thread() {
			public void run() {
				Drawable drawable = loadImageFromUrl(imageUrl);
				imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			}
		}.start();

		return null;
	}

	/*
	 * 得到图片字节流 数组大小
	 */
	public static byte[] readStream(InputStream inStream) {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		try {
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
		} catch (IOException E) {
			E.printStackTrace();
		} finally {
			try {
				outStream.close();
				inStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return outStream.toByteArray();
	}

	public static Drawable loadImageFromUrl(String url) {
		URL m;
		InputStream is = null;
		InputStream temp = null;
		Drawable d = null; // Constants.SDCARD_PATH +
		try {
			if (url.trim().length() > 0) {
				if (!FileUtil.isFileExist(filePath + FileUtil.getFileName(url))) {// 图片是否存在
					m = new URL(url);
					HttpURLConnection conn = (HttpURLConnection) m
							.openConnection();
					conn.setDoInput(true);
					conn.connect();
					is = (InputStream) conn.getContent();
					Bitmap bitmap = BitmapFactory.decodeStream(is);
					d = new BitmapDrawable(bitmap);
					if (FileUtil.isSDCardReady() && isLocalSave) {// 保存于本地文件夹缓存
						is = (InputStream) m.getContent();
						if (FileUtil.isSDCardReady() && isLocalSave) {// 保存于本地文件夹缓存
							FileUtil.writeFileToSDCard(filePath,
									FileUtil.getFileName(url), is);
						}
					}
				} else {
					d = Drawable.createFromPath(filePath
							+ FileUtil.getFileName(url));
				}
			}
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (temp != null) {
					temp.close();
				}
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		return d;

	}

	public static int downloadFile(HttpURLConnection conn, File outputFile) {
		int result = 0;
		String line = null;
		StringBuffer sb = new StringBuffer();
		try {
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader bf = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
				while ((line = bf.readLine()) != null) {
					// 把读到的数据累加起来
					sb.append(line);
				}

			} else {
				result = 1;
			}

		} catch (FileNotFoundException e) {
			result = 1;
		} catch (IOException e) {
			result = 1;
		}
		return result;
	}

	public interface LazyImageCallback {
		/**
		 * TODO
		 * 
		 * @param imageDrawable
		 *            TODO
		 * @param imageUrl
		 *            TODO
		 */
		public void imageLoaded(Drawable imageDrawable, String imageUrl);
	}
}
